<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Model;

/**
 * 文档基础模型
 */
class ModelModel extends CommonModel
{

    protected function _update ($formData, $where = [])
    {
        $data = $formData[$this->name];
        $record = $this->where([
                'id' => $data['id'],
                'extend' => 1
        ])->find();
        
        if ($record && $record['name'] != $data['name'])
        {
            $old_table_name = DB_PREFIX . 'document_' . $record['name'];
            $new_table_name = DB_PREFIX . 'document_' . $data['name'];
            $this->execute("ALTER TABLE {$old_table_name} RENAME {$new_table_name}");
        }
        
        S('DOCUMENT_MODEL_LIST', null);
        return parent::_update($formData, $where);
    }

    protected function _del ($delOptions)
    {
        $record = $this->where([
                'id' => $delOptions['where']['id'],
                'extend' => 1
        ])->find();
        
        if ($record)
        {
            $table_name = C('DB_PREFIX') . 'document_' . strtolower($record['name']);
            $this->execute("DROP TABLE {$table_name}");
        }
        
        M('Attribute')->where(array(
                'model_id' => $delOptions['where']['id']
        ))->delete();
        
        return parent::_del($delOptions);
    }
}
